if (!jsx3.lang.Class.forName("ux.cdb.admin.system.school.SchoolPage")) {

jsx3.Class.defineClass(
        "ux.cdb.admin.system.school.SchoolPage",
        jsx3.gui.Block,
        null,
        function (objRoot) {
            objRoot.prototype.rootDir = "ux/cdb/admin/system/school/docs/";
            objRoot.prototype.namespace = "ux.cdb.admin";

			objRoot.EVENTS = {
				NONE:'None',
				NEW: 'New',
				MODIFY: 'Modify',
				SAVE: 'Save',
				CANCEL: 'Cancel',
				QUERY: 'Query'
			};

			/**
			 * Helper Functions, return a copy function with 
			 * @param fn {Function}
			 * @param scope {Object} 
			 */
			objRoot.prototype.bind = function(fn, scope) {
				scope = scope || this;
				return function() {
					fn.apply(scope, arguments);
				};
			};
			
			/**
			 * Add event to jsx Object
			 * @param name {String} jsx object name or comma-splitted names
			 * @param event {String} event name
			 * @param fct {Function} event handler
			 */
			objRoot.prototype.on = function (name, event, fct) {
				var names = name.split(","), block=this;
				for(var i=0; i<names.length; i++) {
					block = block.get(names[i]);
				}
				block[event] = this.bind(fct);
			};

            objRoot.prototype.property = function(name, token) {
                return ux.megatron.Main.getServer().getDynamicProperty(name, token);
            };
            
			/**
			 * set states of a list of buttons, enable or disable
			 * @param enableBtns {Array} button names to be enabled
			 * @param disableBtns {Array} button names to be disabled
			 */
            objRoot.prototype.setBtns = function (enableBtns, disableBtns) {
                var i;
                if(enableBtns) {
                    for(i=0; i<enableBtns.length; i++) {
                        this.get(enableBtns[i]).enable();
                    }
                }
                if(disableBtns) {
                    for(i=0; i<disableBtns.length; i++) {
                        this.get(disableBtns[i]).disable();
                    }
                }
            };

			/**
			 * This function will be called after deserialize
			 */
            objRoot.prototype.onAfterDeserialize = function() {
/* @JSC :: begin DEBUG */
				jsx3.log('SchoolPage#onAfterDeserialize : Begin onAfterDeserialize ...');
/* @JSC :: end */
			};

			objRoot.prototype.initialize = function() {
/* @JSC :: begin DEBUG */
				jsx3.log('SchoolPage#initialize : Begin initialize ...');
/* @JSC :: end */
                var me = this;
				this.btnEvent = {name:objRoot.EVENTS.NONE};
                this.matrix = this.get("mtxMain");
/* @JSC :: begin DEBUG */
				jsx3.log('SchoolPage#initialize : Begin binding PageWheel ...');
/* @JSC :: end */
				this.pageSize = 15;
				this.totalRecordCount = 0;
				this.currentPage = 1;
				this.totalPages = 1; 
				this.pageLoaded = false;
				
                this.pagebar = this.get("blkPageWheel");

/* @JSC :: begin DEBUG */
				jsx3.log('SchoolPage#initialize : Begin reset panel ...');
/* @JSC :: end */
                this.get("blkListDesc").show();
                this.get("tabbedpane").hide();

/* @JSC :: begin DEBUG */
				jsx3.log('SchoolPage#initialize : Begin binding matrix events ...');
/* @JSC :: end */
                this.matrix.onSelect = this.bind(me.onSelectMatrix, me);
                this.matrix.subscribe(ux.cdb.admin.gui.Matrix.EVENT_CHECKALL, me, me.onCheckMatrix);

                this.on("mtxMain,mcCheckbox,checkbox", "onToggle", me.onCheckMatrix);

/* @JSC :: begin DEBUG */
                jsx3.log('SchoolPage#initialize : Begin binding click event ...');
/* @JSC :: end */
                this.on("btnAdd", "onClick", me.onAddSchool);
                this.on("btnEdit", "onClick", me.onEditSchool);
                this.on("btnDelete", "onClick", me.onDeleteSchool);

                this.on("btnRefresh", "onClick", me.loadSchoolList);
                
				this.on("btnQuery", "onClick", me.doQuery);

				this.on("tabSchool", "onClick", me.loadSchoolDetail);
				this.on("tabCommunication", "onClick", me.loadCommunicationDetail);
				this.on("tabAccount", "onClick", me.loadAccountDetail);
				this.on('btnViewDetailInfo', 'onClick', me.onSelectMatrix);
				
				this.isQuery = false;
				setTimeout(function(){
					//me.loadSchoolList();
				},10);
				
				setTimeout(function(){
	                ux.megatron.Main.loadUIResourceAsync(me.get('tabSchool').getContentPane(), 
	                    "ux.cdb.admin", "ux/cdb/admin/system/school/ui/SchoolDetail.xml", me, function(){
/* @JSC :: begin DEBUG */
		                jsx3.log("begin loading CommunicationDetail.xml");
/* @JSC :: end */
						ux.megatron.Main.loadUIResourceAsync(me.get('tabCommunication').getContentPane(),
		                    "ux.cdb.admin", "ux/cdb/admin/system/school/ui/CommunicationDetail.xml", me, function(){
/* @JSC :: begin DEBUG */
			                jsx3.log("begin loading det_accinfo.xml");
/* @JSC :: end */
							ux.megatron.Main.loadUIResourceAsync(me.get('tabAccount').getContentPane(), 
			                    "ux.cdb.admin", "ux/cdb/admin/system/school/ui/AccountDetail.xml", me, function(){});
						});
					});
				},200);
            };
			
			objRoot.prototype.setCommonCache = function() {
				var cache = ux.cdb.admin.CommonCache.getInstance();
				var school_categ1 = this.get('fieldOfCategory1').getChild(1);
				var school_categ2 = this.get('fieldOfCategory2').getChild(1);
				var province = this.get('fieldOfProvince').getChild(1);
/* @JSC :: begin DEBUG */
				jsx3.log('school_categ1 : ' + school_categ1);
				jsx3.log('school_categ1 cache : ' + cache.getCache('CommonCache_SCHOOL_CATEG1'));
/* @JSC :: end */
				school_categ1.setSourceXML(cache.getCache('CommonCache_SCHOOL_CATEG1'));
				school_categ2.setSourceXML(cache.getCache('CommonCache_SCHOOL_CATEG2'));
				province.setSourceXML(cache.getCache('CommonCache_PROVINCE'));
				setTimeout(function(){
					school_categ1.repaint();
					school_categ2.repaint();
					province.repaint();
				},10);
			};

			/**
			 * Handler for selecting record in Matrix mtxMain
			 */
            objRoot.prototype.onSelectMatrix = function(matrix) {
                var nodes = this.matrix.getSelectedIds();
                if(nodes.length > 0) {
                    this.get("blkListDesc").hide();
                    if(this.get("tabbedpane")) {
                        this.get("tabbedpane").show();
                    }
/* @JSC :: begin DEBUG */
					jsx3.log('TODO:: Load all data from server. current node:' + nodes[0]);
/* @JSC :: end */
                    this.loadDetails(nodes[0]);
                } else {
                    this.get("blkListDesc").show();
                    if(this.get("tabbedpane")) {
                        this.get("tabbedpane").hide();
                    }
                }
            };

			/**
			 * Handler for adding school button
			 */
            objRoot.prototype.onAddSchool = function() {
				this.btnEvent = {name:objRoot.EVENTS.NEW};
                var parent = ux.megatron.Main.getServer().getBodyBlock(); 
                ux.megatron.Main.loadUIResourceAsync(parent,"ux.cdb.admin",
                    "ux/cdb/admin/system/school/builder/ui/BuilderDialog.xml",this, this.onAddBuilderLoaded);
            };
            
			/**
			 * Handler for editing school button
			 */
            objRoot.prototype.onEditSchool = function() {
				this.btnEvent = {name:objRoot.EVENTS.MODIFY};
                var parent = ux.megatron.Main.getServer().getBodyBlock();
                ux.megatron.Main.loadUIResourceAsync(parent,"ux.cdb.admin",
                    "ux/cdb/admin/system/school/builder/ui/BuilderDialog.xml",this, this.onModifyBuilderLoaded);
            };
			
            objRoot.prototype.onAddBuilderLoaded = function(objEvent) {
/* @JSC :: begin DEBUG */
				jsx3.log('SchoolPage#onAddBuilderLoaded.');
/* @JSC :: end */
			};

            objRoot.prototype.onModifyBuilderLoaded = function(objEvent) {
				var wizard = objEvent.obj.get("steppedWizard");
				wizard.editMode = 'Modify';
				if(this.selectedNode)
					wizard.selectedNode = this.selectedNode;
/* @JSC :: begin DEBUG */
				jsx3.log('SchoolPage#onModifyBuilderLoaded. editMode:' + wizard.editMode);
/* @JSC :: end */
            };

			/**
			 * Handler for deleting school button
			 */
            objRoot.prototype.onDeleteSchool = function() {
                var me = this;
                var tipTitle = this.property("@cdb@system@school@DlgDeleteTitle");
                var tipContent = this.property("@cdb@system@school@DlgDeleteContent");
                ux.megatron.Dialog.confirm(tipTitle, tipContent, function(dialog){
                    var nodes = me.matrix.getCheckedNodes();
                    for(var i = 0; i < nodes.size(); i++) {
                        me.matrix.deleteRecord(nodes.getItem(i).getAttribute('jsxid'));
                    }
                    me.matrix.repaintData();
                    me.onCheckMatrix();
                    me.onSelectMatrix();
                    dialog.doClose();
                }, null);
            };
            
			/**
			 * Handler for check some records in Matrix mtxMain
			 */
            objRoot.prototype.onCheckMatrix = function() {
                var nodes = this.matrix.getCheckedNodes();
                if(nodes.size() === 0) {
                    this.setBtns(null, ["btnEdit", "btnDelete"]);
                } else if(nodes.size() == 1) {
                    this.setBtns(["btnEdit", "btnDelete"]);
					this.selectedNode = nodes.get(0);
                } else {//Muilt select
					this.setBtns(["btnDelete"], ["btnEdit"]);
                }
            };

            /**
		             * Load school list into matrix mtxMain
		             */
            objRoot.prototype.loadSchoolList = function() {
				if(jsx3.IDE || ux.megatron.Main.isFileSystem()){ //append mock data
					var _docDir = this.rootDir + "SchoolMatrix" + this.cop + ".xml";
	                ux.megatron.Main.loadResource(_docDir, this.namespace, "SchoolMatrix_0302", "xml");
	                this.matrix.repaint();
	                this.onCheckMatrix();
	                this.onSelectMatrix();
					return;
				}
				var _params = [null,null,null,null,this.currentPage,this.pageSize];
				if(this.isQuery === true){
					var _data = this.get('blkQuery').getData();
					_params = [
								_data.getFirstChild().getAttribute('SchoolName'),
								_data.getFirstChild().getAttribute('Category1'),
								_data.getFirstChild().getAttribute('Category2'),
								_data.getFirstChild().getAttribute('Province'),
								this.currentPage, //current page
								this.pageSize //page size
							  ];
				}
/* @JSC :: begin DEBUG */
				jsx3.log('SchoolInfoUCC#loadSchoolList _params : ' + _params);
/* @JSC :: end */
				ux.megatron.util.Dwr.callDwr("SchoolInfoUCC","getSchoolInfoList",_params,this,
					function(_data){
						if (_data != null && typeof _data == 'object') {
							this.setSchoolList(_data);
/* @JSC :: begin DEBUG */
							jsx3.log('SchoolInfoUCC#getSchoolInfoList data : '+dwr.util.toDescriptiveString(_data, 3));
/* @JSC :: end */
						}
					});
            };
			
			objRoot.prototype.doQuery = function(refresh) {
				if(!refresh) this.currentPage = 1;
				this.isQuery = true;
				this.loadSchoolList();
			};
			
			objRoot.prototype.setSchoolList = function(data) {
				//convert data to CDF
				if(data && data instanceof Object) {
					var tmpCDF = jsx3.xml.CDF.Document.newDocument();
					this.loadPageControler(data.content.page.count); 
					var records = data.content.data;
/* @JSC :: begin DEBUG */
					jsx3.log("SchoolPage#setSchoolList : records : " + dwr.util.toDescriptiveString(records, 3));
/* @JSC :: end */
					for(var i=0,record;record=records[i];i++){
						var jsxid = record.partyId ? record.partyId : i;
						tmpCDF.insertRecord(record,null,false).setAttribute('jsxid',jsxid);
					}
/* @JSC :: begin DEBUG */
					jsx3.log("SchoolPage#setSchoolList : CDF : " + tmpCDF);
/* @JSC :: end */
					
					var _cache = ux.megatron.Main.getServer().getCache();
					_cache.clearById('SchoolMatrix_0302');
					_cache.setDocument('SchoolMatrix_0302',tmpCDF);
	                this.matrix.repaintData();
	                this.onCheckMatrix();
	                this.onSelectMatrix();					
				} else {
					jsx3.log('SchoolPage#setSchoolList cdf data of matrix:' + data);
				}
			};
			
			objRoot.prototype.loadPageControler = function(count) {
				this.totalRecordCount = count;
				this.totalPages = (count%this.pageSize>0) ? (parseInt(count/this.pageSize, 10) + 1) : (count/this.pageSize);
				if(!this.pageLoaded){
					var me = this;
					this.pagebar.initialize();
					this.pagebar.bindWithMatrix(me,me.onPageChange,me.matrix);
					this.pageLoaded = true;
				}
				this.pagebar.setValue(this.currentPage, this.totalPages, this.pageSize, this.totalRecordCount);
			};

			objRoot.prototype.onPageChange = function(msg) {
				this.currentPage = msg.currentPageNumber;
				this.loadSchoolList();
			};

			/**
			 * called when destroy event fired
			 */
            objRoot.prototype.onDestroy = function() {
            };

			objRoot.prototype.__defaultDetail = 'School';

            /**
			* load all details
			*/
			objRoot.prototype.loadDetails = function(node) {
/* @JSC :: begin DEBUG */
				jsx3.log('SchoolPage#loadDetails node is : ' + node);
/* @JSC :: end */
				var _self = this;
				this.detailCDF = {school:null, communication:null, account:null};
				ux.megatron.util.Dwr.callDwr("SchoolInfoUCC","getSchoolDetailInfo",[node],this,
					function(data){
/* @JSC :: begin DEBUG */
						jsx3.log('SchoolInfoUCC#getSchoolDetailInfo data : '+dwr.util.toDescriptiveString(data, 5));
/* @JSC :: end */
						if (data != null && typeof data == 'object') {
							data = data.content.data;
							var tmpCDF = jsx3.xml.CDF.Document;
							if(data[0] && typeof(data[0]) == 'object'){
								this.detailCDF.school = tmpCDF.newDocument();
								this.detailCDF.school.insertRecord(data[0],null,false);
							}
							if(data[1] && typeof(data[1]) == 'object'){
								this.detailCDF.communication = tmpCDF.newDocument();
								this.detailCDF.communication.insertRecord(data[1],null,false);
							}
							if(data[2] && typeof(data[2]) == 'object'){
								this.detailCDF.account = tmpCDF.newDocument();
								this.detailCDF.account.insertRecord(data[2],null,false);
							}
						} else 
							dwr.util.setValue('d0', dwr.util.toDescriptiveString(data, 1));
						
/* @JSC :: begin DEBUG */
						jsx3.log('this.__defaultDetail : ' + _self.get(_self.__defaultDetail));
/* @JSC :: end */
						_self.get('tab' + _self.__defaultDetail).select();
						eval('_self.load' + _self.__defaultDetail + 'Detail();');
					});
			};

			objRoot.prototype.loadSchoolDetail = function() {
/* @JSC :: begin DEBUG */
				jsx3.log('SchoolPage#loadSchoolDetail detailCDF.school = ' + this.detailCDF.school);
/* @JSC :: end */
                if(this.detailCDF && this.detailCDF.school && 
					(this.detailCDF.school instanceof jsx3.xml.CDF.Document))
						this.get("schoolDetail").setData(this.detailCDF.school);
				this.__defaultDetail = 'School';
            };

            objRoot.prototype.loadCommunicationDetail = function() {
/* @JSC :: begin DEBUG */
			jsx3.log('SchoolPage#loadCommunicationDetail detailCDF.communication = ' + this.detailCDF.communication);
/* @JSC :: end */
                if(this.detailCDF && this.detailCDF.communication && 
					(this.detailCDF.communication instanceof jsx3.xml.CDF.Document))
						this.get("communicationDetail").setData(this.detailCDF.communication);
				this.__defaultDetail = 'Communication';
            };

            objRoot.prototype.loadAccountDetail = function() {
/* @JSC :: begin DEBUG */
			jsx3.log('SchoolPage#loadAccountDetail detailCDF.account = ' + this.detailCDF.account);
/* @JSC :: end */
                if(this.detailCDF && this.detailCDF.account && 
					(this.detailCDF.account instanceof jsx3.xml.CDF.Document))
						this.get("accountDetail").setData(this.detailCDF.account);
				this.__defaultDetail = 'Account';
            };

        });
}